<?php
class users {

	public $data = array();
	private $founder = false;
	private $loggedin = false;
	public $fb;
	public $session;

	public function __construct(){
		$this->data = array(
			'id' => (int)false,
			'user_email' => (int)false,
			'user_settings' => (int)false
		);

		$this->loadFB();

		$this->verifyUser();

	}

	public function __set($var, $value){
		global $db;

		if(!$this->isLoggedIn())
			return false;

		return $this->setUserSetting($var, $value);
	}

	private function setUserSetting($var, $value, $id = false){
		global $db;

		if(!$this->isLoggedIn() and (!$id or !is_int($id)))
			return false;

		$id = ($id and is_int($id)) ? $id : $this->data['id'];

		$sql = "SELECT `user_settings` FROM `" . USERS_TABLE . "` WHERE `id` = '{$id}'";
		if($db->query($sql) and $db->affected_rows() == 1) {
			list($data) = $db->fetch_field('user_settings');
			$data = json_decode($data, true);
			if(!is_array($data)){
				$data = array();
			}

			$data[$var] = (is_array($value) and isset($data[$var]) and is_array($data[$var])) ? array_merge($data[$var], $value) : $value;

			$sql = "UPDATE `" . USERS_TABLE . "` SET `user_settings` = '" . $db->real_escape_string(json_encode($data)) . "' WHERE `id` = '{$id}'";
			return $db->query($sql);
		}
		return false;
	}

	public function fb_addUser($fbid, $id = false){
		if($id)
			return $this->setUserSetting('fb', $result, (int)$id);

		$data = array(
			'user_email' => $fbid . "@facebook.com",
			'user_password' => $fbid,
			'user_password_c' => $fbid,
			'user_settings' => array("fb" => array('uid' => $fbid))
		);

		return $this->register($data, false);
	}

	public function fb_removeUser($fbid, $id){
		global $db;

		$sql = "SELECT `id`,`user_email`, `user_settings` FROM `" . USERS_TABLE . "`";
		$sql .= " WHERE `user_settings` REGEXP '\"uid\":\"{$fbid}\"'";

		if($db->query($sql) and $db->affected_rows() > 0){
			list($data) = $db->fetch_assoc();
			$data['user_settings'] = json_decode($data['user_settings'], true);
			if(preg_match('/\@facebook\.com$/', $data['user_email']))
			{
				$this->removeUserData((int)$data['id']);
			}
			elseif(isset($data['user_settings']['fb']) and is_array($data['user_settings']['fb'])){
				// if($id){
				// 	$eh = new emailhash($data['user_email']);
				// 	$fb = new Facebook(FB_API_KEY, FB_SECRET_KEY);
				// 	$result = $fb->api_client->connect_unregisterUsers(array(
				// 			'email_hash' => $eh->getHash()
				// 	));
				// }

				return $this->setUserSetting('fb', false, (int)$data['id']);
			}

		}
		else {
			return false;
		}
	}

	private function isUser($id, $type = 'id'){
		global $db;

		$sql = "SELECT `id` FROM `" . USERS_TABLE . "` WHERE `{$type}` = '{$id}'";

		return ($db->query($sql) and $db->affected_rows() == 1);

	}

	public function removeUserData($id){
		global $db;

		if(is_array($id)){
			$sql = '';
			foreach($id as $oneid){
				$sql .= "DELETE FROM `" . FOLLOWS_TABLE . "` WHERE `user_id` = '{$oneid}';";
				$sql .= "UPDATE `" . USERS_TABLE . "` SET `user_password` = NULL, `user_settings` = NULL, `user_uuid` = NULL WHERE `id` = '{$oneid}' LIMIT 1;";
			}
		}else {
			$sql  = "DELETE FROM `" . FOLLOWS_TABLE . "` WHERE `user_id` = '{$id}';";
			$sql .= "UPDATE `" . USERS_TABLE . "` SET `user_password` = NULL, `user_settings` = NULL, `user_uuid` = NULL WHERE `id` = '{$id}' LIMIT 1;";
		}

		return $db->multi_query($sql);
	}

	public function setSerie($id){
		global $db;

		$pos = in_array($id, $this->data['user_settings']['user_series']);

		if($pos){
			$sql = "DELETE FROM `" . FOLLOWS_TABLE . "` WHERE `user_id` = '{$this->data['id']}' and `series_id` = '{$id}'";
		}
		else
		{
			$sql = "INSERT INTO `" . FOLLOWS_TABLE . "` (`user_id`, `series_id`) VALUES ('{$this->data['id']}', '{$id}')";
			$tv = new TheTvDB();
			$tv->updateAllEpisodes($id);

		}

		return (bool)$db->query($sql);
	}

	public function isFounder(){
		return $this->founder;
	}

	public function isLoggedin(){
		return $this->loggedin;
	}

	public function loginModify($data){
		global $db;

		if($this->loggedin !== true)
			return false;

		if((!valid_email($data['user_email']) or $data['user_email'] != $data['user_email_c']) and (!valid_password($data['user_password']) or $data['user_password'] != $data['user_password_c']))
			return false;

		$sql = "UPDATE `" . USERS_TABLE . "` SET ";
		$sql .= (valid_email($data['user_email'])) ? "`user_email` = '{$data['user_email']}'" : "";
		$sql .= (valid_email($data['user_email']) and valid_password($data['user_password'])) ? " , " : "";
		$sql .= (valid_password($data['user_password'])) ? "`user_password` = MD5('{$data['user_password']}')" : "";
		$sql .= ", `newpwd` = 1 WHERE `user_email` = '{$this->data['user_email']}'";

		return $db->query($sql);
	}

	public function logOut(){
		setcookie('sc_login', '', strtotime('-1 hour'), "/");
		$this->data = array(
			'id' => (int)false,
			'user_email' => (int)false,
			'user_settings' => (int)false
		);
	}

	private function verifyUser(){
		global $db;

		if(isset($_COOKIE['sc_login'])){
			return $this->loadUserData();
		}
		else {
			return $this->verify_fb();
		}
	}

	public function verify_fb(){
		return $this->loadUserData('fb', $this->fb->getUser());
	}

	private function loadUserData($mode = 'cookie', $id = false){
		global $db;

		$sql = "SELECT `id`, `user_email`, `user_settings` FROM `" . USERS_TABLE . "`";

		switch ($mode){
			default:
			case 'cookie':
				$sql .=  " WHERE MD5(`user_uuid`) = '{$_COOKIE['sc_login']}'";
			break;

			case 'fb':
				$sql .= " WHERE `user_settings` REGEXP '\"uid\":\"{$id}\"'";
			break;
		}

		$sql .= " LIMIT 1";

		if($db->query($sql) and $db->affected_rows() == 1) {
			list($udata) = $db->fetch_assoc();
			$udata['user_settings'] = json_decode($udata['user_settings'], true);

			$this->data = array(
				'id' => $udata['id'],
				'user_email' => $udata['user_email'],
				'user_settings' => $udata['user_settings']
			);

			$this->userSeries();

			$this->loggedin = true;
			$this->founder = ($udata['user_email'] == FOUNDER);

			if(isset($udata['user_settings']['fb']) && isset($udata['user_settings']['fb']['uid']) && count($udata['user_settings']['fb']) < 2)
			{
				$fql = "SELECT name, first_name, last_name FROM user WHERE uid = '". $id . "'";
				list($result) = $this->fb->api(array(
					"method" => "fql.query",
					"query" => $fql
				));
				$this->setUserSetting('fb', $result);
			}
		}
		else {
			return false;
		}
	}

	public function login($data, $permanent = false){
		global $db;

		$sql = "SELECT `user_uuid`, `newpwd` FROM `" . USERS_TABLE . "` WHERE `user_email` = '{$data['user_email']}' and `user_password` = IF(`newpwd`, MD5('{$data['user_password']}'), ENCRYPT('{$data['user_password']}','" . SECRET . "')) LIMIT 1";
		if(!$db->query($sql) or $db->affected_rows() != 1)
			return false;
		list($udata) = $db->fetch_assoc();

		if($permanent === true)
			$permanent = strtotime('+2 weeks');
		else
			$permanent = 0;

		setcookie('sc_login', MD5($udata['user_uuid']), $permanent, "/");

		if(!$udata['newpwd'])
		{
			$sql = "UPDATE `" . USERS_TABLE . "` SET `user_password` = MD5('{$data['user_password']}'), `newpwd` = 1 WHERE `user_uuid` = '{$udata['user_uuid']}'";
			$db->query($sql);
		}

		return true;
	}

	public function register($data, $login = true){
		global $db;

		if(!valid_email($data['user_email']) or !valid_password($data['user_password']) or $data['user_password'] != $data['user_password_c'])
			return false;

		$data['user_settings'] = (isset($data['user_settings']) and is_array($data['user_settings'])) ? $data['user_settings'] : array();

		$data['user_settings'] = $db->real_escape_string(json_encode($data['user_settings']));

		$sql = "INSERT INTO `" . USERS_TABLE . "` (`user_email`, `user_password`,`user_settings`, `user_uuid`, `newpwd`) VALUES ('{$data['user_email']}', MD5('{$data['user_password']}'), '". $data['user_settings']."', UUID(), 1) ";

		if($db->query($sql)){
			if($login)
				$this->login($data);
			return true;
		}
		else {
			return "{$sql}\n" . $db->error();
		}

	}
	private function userSeries(){
		global $db;
		$this->data['user_settings']['user_series'] = array();
		$sql = "SELECT `series_id` FROM `" . FOLLOWS_TABLE . "` WHERE `user_id` = '{$this->data['id']}'";
		$db->query($sql);
		$result = $db->fetch_field('series_id');
		$this->data['user_settings']['user_series'] = $result ? $result : array();
	}

	static function listUsers($id = false){
		global $db;

		$sql = "SELECT
			`id`,
			`user_email`,
			`user_settings`,
			`user_registration`,
			`user_uuid`,
			(SELECT COUNT(f.user_id) FROM `" . FOLLOWS_TABLE . "` f WHERE f.`user_id` = u.`id`) as `follows`,
			(SELECT COUNT(r.user_id) FROM `". REVIEW_TABLE . "` r WHERE r.user_id = u.id) as `reviews`,
			(SELECT COUNT(ra.user_id) FROM `". RANKING_TABLE . "` ra WHERE ra.user_id = u.id) as `ratings`
			FROM `" . USERS_TABLE . "` u
		";
		if($id)
			$sql .= " WHERE u.`id` = '{$id}'";
		if($db->query($sql) && $db->affected_rows())
		{
			$rows = $db->fetch_assoc();

			foreach($rows as &$row)
			{
				$row['user_settings'] = json_decode($row['user_settings'], true);
			}

			return ($id) ? $rows[0] : $rows;
		}
		return array();
	}

	public function setUserData($id, array $data)
	{
		if(!$this->isUser($id))
			return false;

		global $db;
		$d = "";
		foreach($data as $key => $date)
		{
			if(!mb_strlen($date))
				continue;

			if($d != "")
				$d .= ", ";

			if($key == 'user_password')
				$date = "ENCRYPT('{$date}','" . SECRET . "')";
			else
				$date = "'{$date}'";
			$d .= " `{$key}` = {$date}";

		}
		$sql = "UPDATE `" . USERS_TABLE . "` SET {$d} WHERE `id` = '{$id}'";

		return $db->query($sql);
	}

	private function loadFB()
	{
		Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
		Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
		$this->fb = new Facebook(array(
		  'appId'  => FB_APP_ID,
		  'secret' => FB_SECRET_KEY,
		  'cookie' => true,
		));

		$this->session = $this->fb->getSession();
		if(!is_array($this->session))
		{
			$this->session = array();
		}
	}

	public function lostPassword($email)
	{
		if($this->isLoggedIn() or !$this->isUser($email, 'user_email'))
			return false;
		global $db;

		$pwd = generate_pwd();
		$sql = "UPDATE `" . USERS_TABLE . "` SET `user_password` = MD5('{$pwd}'), `newpwd` = 1 WHERE `user_email` = '{$email}'";
		if($db->query($sql))
		{
			$text = "Te, vagy valaki ehhez az e-mail címhez tartozó \"Mit nézel?\" regisztrációdhoz új jelszót igényelt.<br /><br />";
			$text .= "Új jelszó: {$pwd}<br /><br />";
			$text .= "Belépés után a \"Felhasználói profil\" menüponton megtudod változtatni.";

			$headers = "From: Mit nézel? <no-reply@sorozat.mine.nu>\r\n";
			$headers .= 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";

			return mail($email, 'Mit nézel? - Új jelszó', $text, $headers);
		}
		return false;

	}

}
?>